﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using CDV.MC.MatrixDriver.WebApp.Models;
using System.Net.Http;
using CDV.MC.MatrixDriver.WebApp.Extensions;
using Newtonsoft.Json;
#if Notify
using WebSocketSharp;
#endif
using CDV.MC.MatrixDriver.WebApp.Service;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace CDV.MC.MatrixDriver.WebApp.Controllers
{
    public class LoginController : Controller
    {
#if Notify
        [HttpPost]
        public ActionResult DoLogin(LoginModel arg)
        {
            if (!ModelState.IsValid)
            {
                var invaildItem = ModelState.Values.Where((modelItem) => { return modelItem.ValidationState == ModelValidationState.Invalid; });
                foreach (var item in invaildItem)
                {
                    ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
                }
                return RedirectToAction("Login", "Matrix", arg);

            }
            try
            {
                var httpClientProvider = (IHttpClientProvider)ServiceLocator.Instance.GetService(typeof(IHttpClientProvider));

                using (var httpClient = httpClientProvider.GetHttpClient(HttpContext))
                {
                    var parameter = new Dictionary<string, string>();
                    parameter.Add("userId", arg.UserId);
                    parameter.Add("pwd", arg.Pwd);
                    var result = httpClient.Post<ValueTuple<bool, string>>("matrix", "Login", parameter);

                    if (result.Item1)
                    {
                        var clientIP = httpClientProvider.GetClientIPAddress(HttpContext).ToString();
                        HttpContext.Session.SetInt32("IsLogin", 1);
                        HttpContext.Session.SetString(HttpClientProvider.ClientIPName, clientIP);

                        var webSocketManager = (IWebSocketManagerService)ServiceLocator.Instance.GetService(typeof(IWebSocketManagerService));

                        webSocketManager.Notify += (sender, e) =>
                        {
                            if (e is MessageEventArgs)
                            {
                                RedirectToAction("Index", "Matrix", (e as MessageEventArgs).Data);

                            }
                            else if (e is ErrorEventArgs)
                            {
                                RedirectToAction("Index", "Matrix", (e as ErrorEventArgs).Message);
                            }
                            //矩阵服务关闭时，Socket连接会断开
                            else if (e is CloseEventArgs)
                            {
                                var ce = e as CloseEventArgs;
                                //异常退出时执行Logout处理
                                if (!ce.WasClean)
                                {
                                    DoLogout(true);
                                    //RedirectToAction("DoLogout", "Login");
                                }
                            }
                            else
                            {

                            }
                        };
                        webSocketManager.AddClientSocket(clientIP);

                        return RedirectToAction("MatrixView", "Matrix");
                    }

                    arg.Result = result.Item2;
                }
            }
            catch (Exception ex)
            {
                arg.Result = ex.Message;
            }
            return RedirectToAction("Login", "Matrix", arg);
        } 
#endif

        [HttpPost]
        public JsonResult Login(LoginModel arg)
        {
            try
            {
                var httpClientProvider = (IHttpClientProvider)ServiceLocator.Instance.GetService(typeof(IHttpClientProvider));

                using (var httpClient = httpClientProvider.GetHttpClient(HttpContext))
                {
                    //var parameter = new Dictionary<string, string>();
                    //parameter.Add("userId", arg.UserId);
                    //parameter.Add("pwd", arg.Pwd);
                    var parameter = new
                    {
                        userId = arg.UserId,
                        pwd = arg.Pwd
                    };
                    var result = httpClient.Post<ValueTuple<bool, string>>("matrix", "Login", parameter);

                    if (result.Item1)
                    {
                        var clientIP = httpClientProvider.GetClientIPAddress(HttpContext).ToString();
                        HttpContext.Session.SetInt32("IsLogin", 1);
                        HttpContext.Session.SetString(HttpClientProvider.ClientIPName, clientIP);
                        result.Item2 = clientIP;
                    }

                    return new JsonResult(result);
                }
            }
            catch (Exception ex)
            {
                return new JsonResult((false, ex.Message));
            }
        }

        public JsonResult DoLogout(bool forceExit)
        {
            try
            {
                var httpClientProvider = (IHttpClientProvider)ServiceLocator.Instance.GetService(typeof(IHttpClientProvider));
                var clientIP = httpClientProvider.GetClientIPAddress(HttpContext);
                if (forceExit)
                {
                    HttpContext.Session.Remove("IsLogin");
                    HttpContext.Session.Remove(HttpClientProvider.ClientIPName);
                    return new JsonResult(true);
                }

                using (var httpClient = httpClientProvider.GetHttpClient(HttpContext))
                {
                    var result = httpClient.Post<ValueTuple<bool, string>>("matrix", "Logout", null);
                    if (result.Item1)
                    {
                        HttpContext.Session.Remove("IsLogin");
                        HttpContext.Session.Remove(HttpClientProvider.ClientIPName);
                        return new JsonResult(true);
                    }
                }
                    return new JsonResult(false);
            }
            catch
            {
                return new JsonResult(false);
            }
        }

#if Notify
        private void Logout(string clientIP)
        {
            try
            {
                var webSocketManager = (IWebSocketManagerService)ServiceLocator.Instance.GetService(typeof(IWebSocketManagerService));
                webSocketManager.RemoveClientSocket(clientIP);

                HttpContext.Session.Remove("IsLogin");
                HttpContext.Session.Remove(HttpClientProvider.ClientIPName);
            }
            catch (Exception ex)
            {
            }
        }
#endif
    }
}